const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate, createDepartmentSchema } = require('../../../lib/validation');

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getDepartments(req, res);
      case 'POST':
        return await createDepartment(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('部门API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

async function getDepartments(req, res) {
  const { parent_id, status = '1', include_stats } = req.query;
  
  let sql = `
    SELECT d.*
    FROM departments d
    WHERE 1=1
  `;
  
  const params = [];
  
  if (parent_id) {
    sql += ' AND d.parent_id = ?';
    params.push(parent_id);
  }
  
  if (status) {
    sql += ' AND d.status = ?';
    params.push(status);
  }
  
  sql += ' ORDER BY d.sort_order, d.name';
  
  const departments = await query(sql, params);
  
  // 如果需要包含统计信息
  if (include_stats === 'true') {
    for (let dept of departments) {
      // 获取部门工单统计
      const ticketStats = await query(`
        SELECT 
          COUNT(*) as total_tickets,
          COUNT(CASE WHEN t.status = 'pending' THEN 1 END) as pending_tickets,
          COUNT(CASE WHEN t.status = 'in_progress' THEN 1 END) as in_progress_tickets,
          COUNT(CASE WHEN t.status = 'resolved' THEN 1 END) as resolved_tickets
        FROM tickets t 
        JOIN users u ON t.user_id = u.id 
        WHERE u.department = ?
      `, [dept.name]);
      
      // 获取部门待办统计
      const todoStats = await query(`
        SELECT 
          COUNT(*) as total_todos,
          COUNT(CASE WHEN td.status = 'pending' THEN 1 END) as pending_todos,
          COUNT(CASE WHEN td.status = 'completed' THEN 1 END) as completed_todos
        FROM todos td 
        JOIN users u ON td.user_id = u.id 
        WHERE u.department = ?
      `, [dept.name]);
      
      dept.stats = {
        tickets: ticketStats[0],
        todos: todoStats[0]
      };
    }
  }
  
  res.status(200).json({
    success: true,
    data: departments
  });
}

async function createDepartment(req, res) {
  const validation = validate(createDepartmentSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const {
    name,
    code,
    parent_id,
    ancestors,
    description,
    contact_phone,
    location,
    budget,
    sort_order = 0
  } = validation.data;

  const result = await query(`
    INSERT INTO departments (
      name, code, parent_id, ancestors, description, 
      contact_phone, location, budget, sort_order
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  `, [name, code, parent_id || null, ancestors || null, description || null, contact_phone || null, location || null, budget || null, sort_order]);

  const newDepartment = await query('SELECT * FROM departments WHERE id = ?', [result.insertId]);

  res.status(201).json({
    success: true,
    message: '部门创建成功',
    data: newDepartment[0]
  });
}

export default authenticateToken(handler);